package com.rep.core.parse;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Maps;
import com.rep.core.parse.model.Tables;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileNotFoundException;
import java.security.InvalidParameterException;
import java.util.Map;

public interface ReplicationParse {

    //缓存{文件地址:Tables}
    Map<String, Tables> TABLES_MAP = Maps.newHashMap();

    /**
     * 解析配置文件
     *
     * @param fileContent
     * @Author: wangye
     * @Date: 2023/2/6 10:56
     * @return:
     **/
    Tables parse(String fileContent) throws  Exception;


    default Tables loadConfig(String filePath) throws Exception {
        String fileContent = getFileContent(filePath);
        return parse(fileContent);
    }


    /**
     * 获取配置文件内容
     *
     * @param filePath resource目录下相对路径
     * @Author: wangye
     * @Date: 2023/2/6 11:13
     * @return:
     **/
    default String getFileContent(String filePath) throws Exception {
        if (StringUtils.isBlank(filePath)){
            throw new InvalidParameterException("filePath is empty");
        }
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        File file = classPathResource.getFile();
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        String content = FileUtil.readString(file, "Utf-8");
        return content;
    }


}
